import {onMounted, reactive, ref} from "vue"
import {getLoginCodeApi, toLoginApi} from "@/apps/admin/api/login";
import guardStore from "@/apps/admin/store/guard"
import tagsStore from "@/apps/admin/store/tags"
import menuStore from "@/apps/admin/store/menu"
import {useRouter} from "vue-router"
import {loginRefreshApi} from "@/apps/admin/api/common";
import {useSuccessDialog} from "@/hooks/DialogMsg";

/**
 * 维持登录
 */
export async function useMaintainLogin() {
    const gstore = guardStore()
    if (gstore.token) {
        const {code, data} = await loginRefreshApi()
        if (code === 200) {
            useProcessLogin({...data.user, token: gstore.token}, data.menu)
        }
    }
}


/**
 * 处理登录
 * @param user
 * @param menu
 */
export function useProcessLogin(user: any, menu: any) {
    const gstore = guardStore()
    const mstore = menuStore()
    gstore.login(user)
    mstore.setMenuData(menu)
}


/**
 * 登录HOOK
 */
export function useLogin() {

    const router = useRouter()
    /**
     * 图像验证码
     */
    const CodeData = reactive({
        image: '',
        sign: ''
    })


    /**
     * 账号密码登录
     */
    const PwdForm = reactive({
        account: '',
        password: '',
        sign: '',
        code: '',
    })


    /**
     * 状态
     */
    const loading = ref(false)


    /**
     * 获取图形验证码
     */
    function getLoginCode() {
        if (loading.value === true) {
            return;
        }
        loading.value = true
        getLoginCodeApi().then(result => {
            if (result.code === 200) {
                CodeData.image = result.data.image
                PwdForm.sign = CodeData.sign = result.data.sign
            }
            loading.value = false
        })
    }

    /**
     * 账号密码登录
     */
    async function byPasswordLogin() {
        if (loading.value === true) {
            return;
        }
        loading.value = true
        const {code, msg, data} = await toLoginApi({...PwdForm})
        if (code === 200) {//登录成功
            useProcessLogin(data.user, data.menu)
            useSuccessDialog(`Hi ${data.user.nickname} 欢迎回来`, '登录提醒').then(() => router.push('/'))
        } else {
            loading.value = false
        }
    }


    onMounted(() => {
        getLoginCode()
    })

    return {
        CodeData,
        PwdForm,
        getLoginCode,
        byPasswordLogin,
        loading
    }
}

/**
 * 退出登录
 */
export function useUserLogout() {
    const gstore = guardStore()
    const tstore = tagsStore()
    const mstore = menuStore()

    /**
     * 清空重置会员值
     */
    function userLogout() {
        gstore.logout()
        tstore.clear()
        mstore.clear()
        location.replace(location.pathname)
    }

    return {
        userLogout
    }
}